﻿var prefs = new gadgets.Prefs();
var msgError = new gadgets.MiniMessage(prefs.getModuleId(), document.getElementById('content_div'));
var authToken = '';

function requestAuth() {
	debugPrint('Requesting auth... ')
	var authURL = 'https://www.google.com/accounts/ClientLogin';
	var authData = 'accountType=HOSTED_OR_GOOGLE&Email=__UP_uName__&Passwd=__UP_uPass__&service=cp&source=gan-contacts-0.1';
	authData = authData.replace('__UP_uName__', prefs.getString('uName'));
	authData = authData.replace('__UP_uPass__', prefs.getString('uPass'));
	var params = {};
	params[gadgets.io.RequestParameters.METHOD] = gadgets.io.MethodType.POST;
	params[gadgets.io.RequestParameters.POST_DATA] = authData;
	gadgets.io.makeRequest(authURL, processAuthResponse, params);
}

function processAuthResponse(resp) {
	if ('' == resp.errors) {
		debugPrint('Succeeded.<br />')
		authToken = (3 <= resp.data.split('\n').length) ? resp.data.split('\n')[2] : null;
		requestContacts();
	}
	else errorPrintResponse(resp);
}

function requestContacts() {
	debugPrint('Requesting contacts... ')
	var contactsURL = 'http://www.google.com/m8/feeds/contacts/default/full?alt=json&max-results=1000';
	var params = {};
	params[gadgets.io.RequestParameters.METHOD] = gadgets.io.MethodType.GET;
	params[gadgets.io.RequestParameters.CONTENT_TYPE] = gadgets.io.ContentType.JSON;
	params[gadgets.io.RequestParameters.HEADERS] = { 'Authorization': 'GoogleLogin ' + authToken, 'GData-Version': '3.0' };
	gadgets.io.makeRequest(contactsURL, processContactsResponse, params);
}

function processContactsResponse(resp) {
	if ('' == resp.errors) {
		debugPrint('Succeeded.<br />')
		renderContacts(resp);
	}
	else errorPrintResponse(resp);
}

function renderContacts(resp) {
	var jsonContacts = resp.data;
	list = jsonContacts.feed.entry;
	debugPrint(list.length.toString() + ' contact(s) retrieved.<br />');

	var divContacts = document.getElementById('contact_container_div');

	// Create title for the whole page
	var pTitle = document.getElementById('title_p');
	pTitle.innerHTML = jsonContacts.feed.title.$t;

	// Create table with contacts, set some attributes and finally add it to the document
	var tableContacts = document.createElement('table');
	tableContacts.setAttribute('width', '100%');
	tableContacts.setAttribute('cellspacing', '0');
	tableContacts.setAttribute('cellpadding', '0');
	divContacts.appendChild(tableContacts);
	
	for (var i = 0; i < list.length; i++) {
		var entry = list[i];
		
		var rowContact = tableContacts.insertRow();
		rowContact.className = (0 == i%2 ? 'rowEven' : 'rowOdd');
		// Email addresses are unique, so let's use them as row ID's
		rowContact.id = entry.gd$email[0].address;
		
		var cellName = document.createElement('td');
		cellName.className = 'cellName';
		cellName.innerHTML = entry.title.$t;
		rowContact.appendChild(cellName);
		
		var cellEmail = document.createElement('td');
		cellEmail.className =  'cellEmail';
		cellEmail.innerHTML = entry.gd$email[0].address;
		rowContact.appendChild(cellEmail);

		debugPrint('Adding: ' + cellName.innerHTML + ' &lt;' + cellEmail.innerHTML + '&gt;<br />');
	}

}

function debugPrint(msgText) {
	if (true == prefs.getBool('fDebug')) document.getElementById('debug_div').innerHTML += msgText;
}

function errorShowResponse(resp) {
	errorShow('Error: ' + resp.errors + '<br />' + 'Data:  ' + resp.data + '<br />' + 'Text:  ' + resp.text);
}

function errorShow(msgText) {
	var msg = msgError.createDismissibleMessage(msgText);
	msg.style.color = 'red';
	msg.style.fontSize = '10pt';
}

function onMouseOver(obj) {
	obj.style.color = 'green';
}

gadgets.util.registerOnLoadHandler(requestAuth);
